import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.tree import DecisionTreeClassifier
from sklearn.preprocessing import LabelEncoder
from sklearn import tree

# 训练样本集合，此处data中的变量保持不变
data = {
    'age': ['<=30', '<=30', '<=30', '<=30', '<=30', '<=30', '<=30', '<=30', '<=30', '<=30', '<=30', '31-51', '31-51',
            '31-51', '31-51', '31-51', '31-51', '31-51', '31-51', '31-51', '31-51', '31-51', '31-51', '>50', '>50',
            '>50'],
    'education': ['H', 'H', 'H', 'H', 'L', 'L', 'L', 'M', 'M', 'M', 'M', 'M', 'M', 'M', 'H', 'H', 'H', 'H', 'H',
                  'L', 'L', 'M', 'M', 'M', 'M', 'M'],
    'area': ['Ⅰ', 'Ⅰ', 'Ⅱ', 'Ⅱ', 'Ⅰ', 'Ⅰ', 'Ⅱ', 'Ⅰ', 'Ⅰ', 'Ⅱ', 'Ⅰ', 'Ⅰ', 'Ⅱ', 'Ⅰ', 'Ⅰ', 'Ⅰ', 'Ⅰ', 'Ⅱ', 'Ⅱ', 'Ⅰ', 'Ⅰ',
             'Ⅱ', 'Ⅰ', 'Ⅰ', 'Ⅱ', 'Ⅰ'],
    'level': ['low', 'high', 'medium', 'high', 'high', 'low', 'low', 'high', 'medium', 'medium', 'low', 'medium',
              'medium', 'low', 'high', 'medium', 'low', 'high', 'low', 'high', 'low', 'high', 'high', 'high', 'high','medium'],
    'class': ['bad', 'good', 'bad', 'good', 'good', 'good', 'good', 'good', 'good', 'good', 'good', 'good', 'good',
              'bad', 'good', 'good', 'good','bad', 'bad', 'good', 'good', 'bad', 'good','bad', 'bad', 'good']
}

# 创建DataFrame
df_data = pd.DataFrame(data)

# 将类别变量转换为数字（Label Encoding）
le_encoder = LabelEncoder()
df_encoded_data = df_data.copy()
for col in df_encoded_data.columns:
    if df_encoded_data[col].dtype == 'object':
        df_encoded_data[col] = le_encoder.fit_transform(df_encoded_data[col])

# 提取特征和目标变量
features = df_encoded_data.drop(columns='class')
target = df_encoded_data['class']

# 训练ID3决策树
decision_tree_clf = DecisionTreeClassifier(criterion='entropy', max_depth=3)
decision_tree_clf.fit(features, target)

# 获取类别标签
original_class_names = le_encoder.inverse_transform(decision_tree_clf.classes_)

# 输出决策树结构
from sklearn.tree import export_text
tree_rules_text = export_text(decision_tree_clf, feature_names=list(features.columns))
print(tree_rules_text)